/**
 * update_system is a CGI program that will upload a file specified in an html 
 * file to the server.  It is assumed that file is a gzip compressed tar archive.
 * The archive will be expanded and the file install.sh executed from the top 
 * directory in the archive.
 *
 * 23oct2006  GJ  ORIGINAL VERSION (based on gcgiFileUploadTest.c from libgcgi).
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "gcgi.h"

static const char* const strTypes[] = {
    "text", 
    "image", 
    "audio", 
    "video", 
    "application", 
    "multipart", 
    "message", 
    "unknown"
};

static const char* const strEncodings[] = {
    "7bit", 
    "8bit", 
    "binary", 
    "quoted-printable", 
    "base64", 
    "unknown"
};

int main (int argc, char *argv[], char *envp[]) 
{
  FILE *op;
  MimeEncoding  enc;
  MimeType      type;
  char         *file, *fname, *subtype; 
  int           len, truncated;
  char fpath[256];
  char syscmd[256];

  printf("Content-type: text/html\n\n");
  printf("<html>\n<body>\n");
  printf("<h1>Update System</h1>\n");

  /* Set Limits: field limit, query limit */
  gcgiSetLimits(10485760, 0);

  if (initCgi() < 0) {
    printf("Unable to parse CGI query.\n");
    return -1;
  }
  
  gcgiFieldSize("uploaded_file", &len);
  file = (char *) malloc(len);

  gcgiFetchData("uploaded_file", file, len, &type, &subtype, &enc, &fname, &truncated);

  if (truncated) {
    printf("Content-Type: text/plain\n\n");
    printf("File size has exceeded limit.  Pick something smaller.\n");
  }
  else {
    printf("Content-Type: %s/%s\n", strTypes[type], subtype);
    printf("Content-Disposition: attachment; filename=\"%s\"\n", fname);
    printf("Content-Length: %d\n\n", len);

    strcpy(fpath,"/var/www/images/tmp/");
    strcat(fpath,fname);
    printf("fpath=%s\n",fpath);

    op=NULL;
    op=fopen(fpath,"w");
    if (op==NULL) {
      printf("Error Opening Output File %s for output\n",fpath);
    }
    else {
         printf("Writing File\n");
	 fwrite(file, sizeof(char), len, op);
	 fclose(op);
    }
    
  }

  sprintf(syscmd,"/bin/tar -xf %s",fpath);
  printf("syscmd = %s<br>\n",syscmd);
  system(syscmd);

  printf("</html>\n</body>\n");


  free(file);
  free(subtype);
  free(fname);

  freeCgi();

  return 0;
}
